#!/bin/bash

# Make sure that you apache-tomcat exist in PATH_TO_TOMCAT
PATH_TO_OPT="/opt"
CURRENT_USER=$USER

function setTomcatOwner {
   echo "$PASSWORD" | sudo -S chown -R $CURRENT_USER:$CURRENT_USER $PATH_TO_OPT
}

function setPermissionToTomcat {
   echo "$PASSWORD" | sudo -S chmod -R 777 $PATH_TO_OPT
}

function setTomcat {
   setTomcatOwner
   echo "1) => Owner, for $PATH_TO_OPT and everything inside it, has been changed to $CURRENT_USER"
   setPermissionToTomcat
   echo "2) => All permissions to files inside $PATH_TO_OPT files have been set"
}

function runMySqlQuery {
   QUERY=$1

   mysql -u root -p$PASSWORD --disable-column-names --execute="$QUERY"
}

function readPassword {
   printf "Enter your password: "
   stty -echo
   read PASSWORD
   stty echo
   printf '\n'
}

function setMySql {
   MY_SQL_USER="'$CURRENT_USER'@'localhost'"
   numberOfUsers=$(runMySqlQuery "SELECT COUNT(*) FROM mysql.user WHERE user = '$CURRENT_USER' AND host = 'localhost'")
   
   if [ "$numberOfUsers" == "0" ]; then
      runMySqlQuery "CREATE USER $MY_SQL_USER;"
      echo "3) => MySql user ('$CURRENT_USER'@'localhost') has been created"
      runMySqlQuery "GRANT ALL PRIVILEGES ON *.* TO $MY_SQL_USER WITH GRANT OPTION;"
      echo "4) => Permission for user '$CURRENT_USER'@'localhost' has been granted"
   fi
}

function main {
   readPassword
   setTomcat
   setMySql
}

# Run main function
main
 
